﻿/**
* File: XmjckhxxService.cs
* Author: 汪杰
* Create Time:2025/2/18 15:06:56
* Email:15200358008@139.com
* 代码由TMCodeGenerator自动生成
**/
using AutoMapper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JSLCloud.Attributes;
using JSLCloud.App.Models.Xmjckhxx;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using JSLCloud.Models;
using JSLCloud.Utilities.SqlSugar;
using JSLCloud.Utilities.WebApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections;


namespace JSLCloud.App.Mes.Service
{
    /// <summary>
    /// IXmjckhxxService 实现类
    /// </summary>
    [UseDI(ServiceLifetime.Scoped,typeof(IXmjckhxxService))]
    public class XmjckhxxService : IXmjckhxxService
    {
        private readonly IDbContext _db;//数据库操作实例对象
        private readonly ILogger<XmjckhxxService> _log;//日志操作实例对象
        private readonly IMapper _mapper;//AutoMapper实例
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public XmjckhxxService(IDbContext dbContext, ILogger<XmjckhxxService> logger,IMapper mapper)
        {
            _db = dbContext;
            _log = logger;
            _mapper = mapper;
        }
        
        /// <summary>
        /// 获取xm_jc_khxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<XmjckhxxQueryModel>>> GetAsync(RequestGet requestObject)
        {
            try
            {
                List<XmjckhxxQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmjckhxxDbModel>();
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }
                
                //查询未删除数据
                query.Where("DELETEFLAG = 0");
                
                //排序条件
                if(requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        if (item.Condition.ToLower() != "asc" 
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }
                
                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
						(t) => new XmjckhxxQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Khbm = t.Khbm,
							Khmc = t.Khmc,
							Khjc = t.Khjc,
							Kyrq = t.Kyrq,
							Zczj = t.Zczj,
							Ygrs = t.Ygrs,
							Lxr = t.Lxr,
							Lxdh = t.Lxdh,
							Gsdz = t.Gsdz,
							Shdz = t.Shdz,
							Khly = t.Khly,
							Khzt = t.Khzt,
                            Bz = t.Bz
						})
                        .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
						(t) => new XmjckhxxQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Khbm = t.Khbm,
							Khmc = t.Khmc,
							Khjc = t.Khjc,
							Kyrq = t.Kyrq,
							Zczj = t.Zczj,
							Ygrs = t.Ygrs,
							Lxr = t.Lxr,
							Lxdh = t.Lxdh,
							Gsdz = t.Gsdz,
							Shdz = t.Shdz,
							Khly = t.Khly,
							Khzt = t.Khzt,
                            Bz = t.Bz
						})
                        .ToListAsync();
                }
                    
                //返回执行结果
                return ResponseUtil<List<XmjckhxxQueryModel>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<XmjckhxxQueryModel>>.FailResult(null, ex.Message);
            }
        }
        
        /// <summary>
        /// 新增xm_jc_khxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，新增操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PostAsync(RequestPost<XmjckhxxAddModel> requestObject)
        {
            try
            {
                //如果没有新增数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                var result = false;
                //批量新增的优先级高于单条数据新增，且只会执行一个新增操作
                if(requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    var addList = _mapper.Map<List<XmjckhxxAddModel>, List<XmjckhxxDbModel>>(requestObject.PostDataList);
                    var oldList = await _db.Instance.Queryable<XmjckhxxDbModel>().Where(p => p.Deleteflag == 0).ToListAsync();
                    var count = oldList.Count;
                    foreach (var item in addList)
                    {                        
                        //已经存在该体系编码则更新
                        if (oldList.Any(p => p.Khbm == item.Khbm))
                        {
                            await _db.Instance.Updateable<XmjckhxxDbModel>()
                                .SetColumns(p => p.Khmc == item.Khmc)
                                .SetColumns(p => p.Khjc == item.Khjc)
                                .SetColumns(p => p.Kyrq == item.Kyrq)
                                .SetColumns(p => p.Zczj == item.Zczj)
                                .SetColumns(p => p.Ygrs == item.Ygrs)
                                .SetColumns(p => p.Lxr == item.Lxr)
                                .SetColumns(p => p.Lxdh == item.Lxdh)
                                .SetColumns(p => p.Gsdz == item.Gsdz)
                                .SetColumns(p => p.Shdz == item.Shdz)
                                .SetColumns(p => p.Khly == item.Khly)
                                .SetColumns(p => p.Bz == item.Bz)
                                .Where(p => p.Khbm == item.Khbm)
                                .ExecuteCommandAsync();
                        }
                        else
                        {
                            //item.Khbm = $"{DateTime.Now:yyMMdd}" + $"{count + 1}".PadLeft(4, '0');
                            await _db.Instance.Insertable(item).ExecuteCommandAsync();
                            count++;
                        }
                    }
                    result = true;
                }
                else
                {
                    var addModel = _mapper.Map<XmjckhxxDbModel>(requestObject.PostData);
                    var count  = await _db.Instance.Queryable<XmjckhxxDbModel>().Where(p => p.Deleteflag == 0).CountAsync();
                    //addModel.Khbm = $"{DateTime.Now:yyMMdd}" + $"{count + 1}".PadLeft(4, '0');
                    result = await _db.Instance.Insertable(addModel).ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "新增数据失败!");
            }
            catch(Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 修改xm_jc_khxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PutAsync(RequestPut<XmjckhxxEditModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmjckhxxEditModel>, List<XmjckhxxDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList)
                        .IgnoreColumns(p => new { p.Createid, p.Createtime,p.Createname })
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmjckhxxDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel)
                        .IgnoreColumns(p => new { p.Createid, p.Createtime,p.Createname })
                        .ExecuteCommandAsync() > 0;
                }
                
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 删除xm_jc_khxx数据
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> DeleteAsync(RequestDelete<DeleteModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有删除数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData、PostDataList不能都为null");
                //批量删除的优先级高于单记录删除
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量删除
                    var ids = requestObject.PostDataList.Select(p => p.ID);
                    result = await _db.Instance.Updateable<XmjckhxxDbModel>()
                            .SetColumns(p => p.Deleteflag == 1)
                            .Where(p => ids.Contains(p.ID))
                            .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录删除
                    result = await _db.Instance.Updateable<XmjckhxxDbModel>()
                        .SetColumns(p => p.Deleteflag == 1)
                        .Where(p => p.ID == requestObject.PostData.ID)
                        .ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "删除数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
    }
}
